package com.company.cloud.work.modules.mgr.controller;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.common.server.constant.IRelBusiType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.cloud.work.modules.base.entity.WorkLogInfo;
import com.company.cloud.work.modules.base.service.WorkLogInfoService;
import com.company.cloud.work.modules.cache.models.WorkLogModel;
import com.company.cloud.work.modules.cache.utils.CrmWorkChangeUtils;
import com.company.cloud.work.modules.mgr.controller.req.WorkLogQuerey4PageParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkLogSaveParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkLogUpdateParam;
import com.company.cloud.work.modules.mgr.service.WorkReceiptMgrService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/mgr/crm/workLog")
@Api(tags = "CRM_Mgr_工作日志管理")
public class WorkLogMgrController {

	@Autowired
	private WorkLogInfoService workLogInfoService;

	@Autowired
	private UserRemoteService userRemoteService;

	@Autowired
	private WorkReceiptMgrService workReceiptMgrService;

	@PostMapping("/query")
	@ApiOperation(value = "查询", response = WorkLogModel.class)
	public BaseResult query(@RequestBody WorkLogQuerey4PageParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		String copyUserId = null;
		String commentUserId = null;
		if (CheckUtils.hasInt(params.getCopyUserId())) {
			copyUserId = StrUtil.format(",{},", params.getCopyUserId());
		}
		if (CheckUtils.hasInt(params.getCommentUserId())) {
			commentUserId = StrUtil.format(",{},", params.getCommentUserId());
		}
		IPage<WorkLogInfo> page = workLogInfoService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<WorkLogInfo>().eq("rows_state", EnabledEnum.ENABLED.getCode())
						.eq("company_no", userInfo.getCompanyNo())
						.eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
						.eq(StringUtils.hasText(params.getWorkType()), "work_type", params.getWorkType())
						.like(StringUtils.hasText(copyUserId), "copy_user_ids", copyUserId)
						.like(StringUtils.hasText(commentUserId), "comment_user_ids", commentUserId));

		if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
			return BaseResult.ok();
		}
		Set<Integer> userIds = new HashSet<Integer>();
		page.getRecords().forEach(item -> {
			if (CheckUtils.hasInt(item.getUserId())) {
				userIds.add(item.getUserId());
			}
			userIds.addAll(StrSplitUtils.parse2list(item.getCopyUserIds(), Integer.class));
			userIds.addAll(StrSplitUtils.parse2list(item.getCommentUserIds(), Integer.class));
		});

		BaseClientResult<Map<Integer, UserSimple>> userMapResult = userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userMapResult);
		IPage<WorkLogModel> data = page.convert(new Function<WorkLogInfo, WorkLogModel>() {
			@Override
			public WorkLogModel apply(WorkLogInfo entity) {
				return CrmWorkChangeUtils.getWorkLogModel(entity, userMap);
			}
		});
		return BaseResult.ok(data);
	}

	@PostMapping("/add")
	@ApiOperation(value = "新增", response = BaseResult.class)
	@StaffLogc(title = "新增工作日志", action = "新增工作日志", actionAdo = "工作日志")
	public BaseResult add(@RequestBody WorkLogSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		WorkLogInfo entity = new WorkLogInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setUserId(userInfo.getId());
		entity.setWorkSummary(params.getWorkSummary());
		entity.setWorkPlan(params.getWorkPlan());
		entity.setWorkExperience(params.getWorkExperience());
		entity.setWorkType(params.getWorkType());
		entity.setStartDate(params.getStartDate());
		entity.setEndDate(params.getEndDate());
		entity.setCopyUserIds(StrSplitUtils.list2string_prefix(params.getCopyUserIds()));
		entity.setCommentUserIds(StrSplitUtils.list2string_prefix(params.getCommentUserIds()));
		entity.setIsReceipt(params.getIsReceipt());
		entity.addCreateParam(userInfo);
		entity.addEditParam(userInfo);
		workLogInfoService.save(entity);
		return BaseResult.ok();
	}

	@PostMapping("/edit")
	@ApiOperation(value = "修改", response = BaseResult.class)
	@StaffLogc(title = "修改工作日志", action = "修改工作日志", actionAdo = "工作日志")
	public BaseResult edit(@RequestBody WorkLogUpdateParam params) {
		ValidatorUtils.validate(params);
		WorkLogInfo entity = workLogInfoService.getById(params.getId());
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		entity.setWorkSummary(params.getWorkSummary());
		entity.setWorkPlan(params.getWorkPlan());
		entity.setWorkExperience(params.getWorkExperience());
		entity.setWorkType(params.getWorkType());
		entity.setStartDate(params.getStartDate());
		entity.setEndDate(params.getEndDate());
		entity.setCopyUserIds(StrSplitUtils.list2string_prefix(params.getCopyUserIds()));
		entity.setCommentUserIds(StrSplitUtils.list2string_prefix(params.getCommentUserIds()));
		entity.setIsReceipt(params.getIsReceipt());
		entity.addEditParam(userInfo);
		workLogInfoService.updateById(entity);
		return BaseResult.ok();
	}

	@GetMapping("/get")
	@ApiOperation(value = "获取", response = WorkLogModel.class)
	public BaseResult get(@RequestParam("id") Integer id) {
		WorkLogInfo entity = workLogInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		Set<Integer> userIds = new HashSet<Integer>();
		if (CheckUtils.hasInt(entity.getUserId())) {
			userIds.add(entity.getUserId());
		}
		userIds.addAll(StrSplitUtils.parse2list(entity.getCopyUserIds(), Integer.class));
		userIds.addAll(StrSplitUtils.parse2list(entity.getCommentUserIds(), Integer.class));

		BaseClientResult<Map<Integer, UserSimple>> userMapResult = userRemoteService.getUserMapByIds(userIds);
		WorkLogModel data = CrmWorkChangeUtils.getWorkLogModel(entity, BaseClientResult.getResultData(userMapResult));
		if (YNEnum.YES.getCode().equals(entity.getIsReceipt())) {
			workReceiptMgrService.save(IRelBusiType.CRM_Work_Log_ID, entity.getId().toString(), null, userInfo);
		}
		return BaseResult.ok(data);
	}

	@GetMapping("/remove")
	@ApiOperation(value = "删除", response = BaseResult.class)
	@StaffLogc(title = "删除工作日志", action = "删除工作日志", actionAdo = "工作日志")
	public BaseResult remove(@RequestParam("id") Integer id) {
		WorkLogInfo entity = workLogInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		entity.setRowsState(EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		workLogInfoService.updateById(entity);
		return BaseResult.ok();
	}

}
